package com.guess.lolguessing.service.impl;

import com.guess.lolguessing.context.BaseContext;
import com.guess.lolguessing.domain.po.Comment;
import com.guess.lolguessing.domain.po.Guessing;
import com.guess.lolguessing.domain.po.Matches;
import com.guess.lolguessing.domain.po.UserGuessing;
import com.guess.lolguessing.exception.LoginFailedException;
import com.guess.lolguessing.mapper.UserGuessingMapper;
import com.guess.lolguessing.result.Result;
import com.guess.lolguessing.service.IUserGuessingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-24
 */
@Service
@RequiredArgsConstructor
public class UserGuessingServiceImpl extends ServiceImpl<UserGuessingMapper, UserGuessing> implements IUserGuessingService {

    private final UserPointsServiceImpl userPointsService;
    private final MatchesServiceImpl matchesService;
    private final GuessingServiceImpl guessingService;
    @Override
    public Result bet(Integer matchId, Integer teamId, Integer betAmount) {
        Long userId = BaseContext.getCurrentId();
        System.out.println("竞猜积分是" + betAmount);
        synchronized (userId.toString().intern()) {
            int amount = userPointsService.getPointsByUserId(userId);
            if (betAmount > amount) {
                throw new LoginFailedException("输入的积分大于用户的积分");
            }

            Matches match = matchesService.getById(matchId);
            if (LocalTime.now().isAfter(LocalTime.from(match.getStartTime()))) {
                throw new LoginFailedException("当前已经过了可下注的时间");
            }

            // 更新用户积分，减少下注的积分
            userPointsService.updatePointsByUserId(userId, amount - betAmount);

            // 创建用户竞猜记录
            UserGuessing userGuessing = new UserGuessing();
            userGuessing.setUserId(Math.toIntExact(userId));
            userGuessing.setPoints(betAmount);  // 使用下注的积分
            userGuessing.setMatchId(matchId);
            userGuessing.setTeamId(teamId);
            userGuessing.setStartTime(LocalDateTime.now());
            userGuessing.setEndTime(match.getEndTime().plusHours(1));

            // 更新竞猜积分
            Guessing guessing = guessingService.getByMatchId(matchId);
            if (guessing.getTeamAId().equals(teamId)) {
                guessingService.updateA(matchId, betAmount);
            } else {
                guessingService.updateB(matchId, betAmount);
            }

            // 保存用户的竞猜记录
            this.save(userGuessing);
        }

        return Result.success();
    }
}
